<?php defined('SYSPATH') or die('No direct script access.');

class Model_Services_RawSignal extends Model{
	
	public $rawsignal;
	public $rawsample;
	
	public function __construct($id=false){
		if ($id) $this->rawsignal = $this->get($id);
	}
	
	public function count(){
		return ORM::factory("dao_rawsignal")->count_all();
	}
	
	public function getList($page=false, $limit = false){
		
		if ($page && $limit){
			$offset = ($page - 1) * $limit;
			return ORM::factory("dao_rawsignal")->order_by("creationdate","desc")->limit($limit)->offset($offset)->find_all()->as_array();
		}
		
		return ORM::factory("dao_rawsignal")->order_by("creationdate","desc")->find_all()->as_array();
	}
	
	public function getCondition($orderfield, $ordertype, $start,$limit){
		return ORM::factory("dao_rawsignal")->order_by($orderfield,$ordertype)->limit($limit)->find_all()->as_array();
	}
		
	public function get($id){
		return ORM::factory("dao_rawsignal")->find($id);
	}
	
	public function getFilename(){
		return $this->rawsignal->filename;
	}
	
	public function getSamples($id=false){
		if ($id){
			$this->rawsample = ORM::factory("dao_rawsample")->where('raw_signals_id','=',$id)->find();
		}else{
			$this->rawsample = ORM::factory("dao_rawsample")->where('raw_signals_id','=',$this->rawsignal->id)->find();
		}
				
		$segment = Model::factory("segment");
		$segment->unserialize($this->rawsample->content);
		return $segment;
		
	}
	
	public function save($id,array $data){
				
		$this->rawsignal = ($id > 0) ? ORM::factory("dao_rawsignal",$id) : ORM::factory("dao_rawsignal");
		$this->rawsignal->filename = $data["filename"];
		$this->rawsignal->creationdate = DB::expr('NOW()');
		$this->rawsignal->sampling_periods_id = $data["sampling_period"];
		$this->rawsignal->save();
		
				
		$this->rawsample = ORM::factory("dao_rawsample");
		$this->rawsample->content = $data["signal"];
		$this->rawsample->raw_signals_id = $this->rawsignal->id;
		$this->rawsample->save();
				
		return $this->rawsignal->id;
	}
	
	public function delete($id){
		$this->rawsignal = ORM::factory("dao_rawsignal",$id);
		$this->rawsignal->delete();
		return $id;
	}
	
	
}
